package com.baihui.taobao.transition;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baihui.taobao.authorize.TaoBaoSessionInfo;
import com.baihui.taobao.db.CommonDAO;
import com.baihui.taobao.db.DBConnectionMgr;
import com.baihui.taobao.db.UserDAO;
import com.baihui.taobao.util.Util;
import com.baihui.taobao.vo.BUser;
import com.taobao.api.ApiException;
import com.taobao.api.TaobaoObject;
import com.taobao.api.domain.Trade;
import com.taobao.api.domain.User;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.request.UsersGetRequest;
import com.taobao.api.response.UserGetResponse;
import com.taobao.api.response.UsersGetResponse;

/**
 * Created by Kevin. User: HSZM1106-0312 Date: 11-12-24 Time: 下午7:54
 */
public class UserCase extends Cases implements IViewProgressSupport {

	public UserCase(TaoBaoSessionInfo info) {
		super(info);
	}

	public User getUserInfo(String nickName) throws Exception {
		UserGetRequest req = new UserGetRequest();
		// req.setFields("user_id,uid,nick,sex,buyer_credit,seller_credit,location,created,last_visit,birthday,type,status,alipay_no,alipay_account,alipay_account,email,consumer_protection,alipay_bind");
		req.setFields(parseFields(User.class));
		req.setNick(nickName);
		try {
			UserGetResponse response = getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
			User user = response.getUser();
			if (user == null) {
				throw new Exception(response.getBody());
			}
			return user;
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	public List<User> getUsersInfo(String nickNames) throws Exception {
		if ("".equals(nickNames)) {
			return new ArrayList<User>();
		}
		UsersGetRequest req = new UsersGetRequest();
		req.setFields(parseFields(User.class));
		req.setNicks(nickNames);
		try {
			// UsersGetResponse response = getTaoBaoClient().execute(req,
			// getSessionInfo().getTopSession());
			UsersGetResponse response = getTaoBaoClient().execute(req);
			List<User> users = response.getUsers();
			if (users == null) {
				throw new Exception(response.getBody());
			}
			return users;
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	/**
	 * 从淘宝导入成交买家信息 1.每批只能导入40个 2.我们限定最多一次性导入MAX_COUNT个
	 * 3.每次处理40个后，需要更新lotDealNick和importOrderStatus表
	 * 
	 * @param userType
	 * @param sellerid
	 * @param lotInfo
	 * @throws Exception
	 */
	public void exportUserToDB(String userType, long sellerid,
			List<String> tradeNickList) throws Exception {
		// 从数据库中查找MAX_COUNT个nick
		CommonDAO commonDAO = new CommonDAO();
		markImportProgress(55);
		List<BUser> bUsers = new ArrayList<BUser>();
		List<String> updateUsersSql = new ArrayList<String>();
		// tbuser表里已经存在的数据
		List<String> nickList = (List<String>) commonDAO.findListString(
				"Select nick from tbuser where sellerid = ? ",
				new Object[] { sellerid });
		for (String nick : tradeNickList) {
			if (nickList.contains(nick)) {
				updateUsersSql
						.add("update tbuser set exported = 2 where nick = '"
								+ nick + "' and sellerid = " + sellerid);
			} else {
				User user = getUserInfo(nick);
				BUser tmp = new BUser();
				Util.copy(tmp, user);
				tmp.setUserType(userType);
				tmp.setSellerid(sellerid);
				tmp.setExported(0);
				bUsers.add(tmp);
			}
		}
		Connection cn = null;
		try {
			cn = DBConnectionMgr.getConnection();
			// 插入数据
			UserDAO userDAO = new UserDAO();
			if (bUsers != null && bUsers.size() > 0) {
				userDAO.insertUsers(bUsers, cn);
				bUsers.clear();
			}
			if (updateUsersSql != null && updateUsersSql.size() > 0) {
				userDAO.updateAndInsert(updateUsersSql, cn);
				updateUsersSql.clear();
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (cn != null)
				cn.close();
		}
		markImportProgress(72);
	}

	/**
	 * 从tbuser表中过滤已经存在于数据库中的记录.
	 * 
	 * @param taobaoobjects
	 * @param key
	 * @param table
	 * @return
	 * @throws Exception
	 */
	public String filterTBuser(String nicks, long sellerid) throws Exception {
		String nicksString = "";
		StringBuffer nicksStringBuff = new StringBuffer();
		StringBuffer subNicksStringBuff = new StringBuffer();
		// List<String> nickList = new ArrayList<String>();
		// Iterator k = nicks.iterator();
		// while(k.hasNext()){
		// nickList.add(String.valueOf(k.next()));
		// }
		if (!"".equals(nicks)) {
			String[] nickStrings = nicks.split(",");
			for (String nick : nickStrings) {
				nicksStringBuff.append("'").append(nick).append("'")
						.append(",");
			}
			// 去除重复数据
			String sql = "Select nick from tbuser where sellerid = ? and nick in (?) ";
			CommonDAO commonDAO = new CommonDAO();
			List<Map> nicksList = commonDAO.findAllObject(
					sql,
					new Object[] {
							sellerid,
							nicksStringBuff.substring(0,
									nicksStringBuff.length() - 1) });
			if (nicksList != null && nicksList.size() > 0) {
				for (Map nick : nicksList) {
					subNicksStringBuff.append(nick.get("nick"));
					subNicksStringBuff.append(",");
				}
				nicksString = subNicksStringBuff.toString();
			}
			if (!"".equals(nicksString)
					&& nicksString.lastIndexOf(",") == nicksString.length() - 1) {
				nicksString = nicksString.substring(0,
						nicksString.lastIndexOf(","));
			}
		}
		return nicksString;
	}

	public static void main(String[] a) {
		List str = new ArrayList();
		str.add("货物运输");
		str.add("物流运输");
		CommonDAO commonDAO = new CommonDAO();
		List nickList = new ArrayList();
		try {
			nickList = commonDAO
					.findAllObject("Select nick from tbuser where sellerid = "
							+ "'" + 350514064 + "'");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (nickList.contains("超宝宝168")) {
		} else {

		}

		// String str = "货物运输,物流运输";
		// System.out.println(str.replaceAll("(.*,).*,\\1+", "$1"));
		System.out.println(str.contains("物流货物运输"));

	}

	public void importUserFromTaobao(List<String> allBuyer, String userType,
			Connection cn, long sellerid) throws Exception {
		if (allBuyer == null || allBuyer.size() <= 0)
			return;
		List<TaobaoObject> bUsers = new ArrayList<TaobaoObject>();
		/**
		 * nick限制一次性最多只能取40个.
		 */
		int count = 39, startIndex = 0;
		List<String> subList = Util.subList(allBuyer, startIndex, count);
		while (subList != null && subList.size() > 0) {
			StringBuilder nicks = new StringBuilder();
			for (String nick : subList) {
				nicks.append(nick).append(",");
			}
			String nickStr = nicks.toString();
			if (nickStr.lastIndexOf(",") > -1) {
				nickStr = nickStr.substring(0, nickStr.length() - 1);
			}
			List<User> userList = getUsersInfo(nickStr);

			List<Long> excludes = filter(userList, "userId", "tbuser");
			// 拼装数据

			if (userList == null || userList.size() <= 0)
				return;
			for (User user : userList) {
				if (excludes.contains(user.getUserId()))
					continue;
				BUser tmp = new BUser();
				Util.copy(tmp, user);
				tmp.setUserType(userType);
				tmp.setExported(0);
				tmp.setSellerid(sellerid);
				bUsers.add(tmp);
			}

			startIndex = startIndex + count;
			subList = Util.subList(allBuyer, startIndex, count);
		}

		// 插入数据
		UserDAO userDAO = new UserDAO();
		userDAO.insert(bUsers, cn);
	}

	public User getUserInfo(TaoBaoSessionInfo visitor_id) throws Exception {
		UserGetRequest req = new UserGetRequest();
		req.setFields(parseFields(User.class));
		try {
			UserGetResponse response = getTaoBaoClient().execute(req,
					getSessionInfo().getTopSession());
			User user = response.getUser();
			if (user == null) {
				throw new Exception(response.getBody());
			}
			return user;
		} catch (ApiException e) {
			throw new Exception(e);
		}
	}

	public void markImportProgress(int progress) {
		// System.out.println("当前进度：" + progress + "%");
		getSessionInfo().setOrderImportProgress(progress);
	}

	public int viewImportProgress() {
		return getSessionInfo().getOrderImportProgress();
	}
}
